package com.fub.guidance;

import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;

import com.fub.util.database.databaseHelper.UpdatesDatabaseManager;

public class RoomDataDAO {
	private static int KEY_POSITION = 2;
	private static int VALUE_POSITION = 3;
	private SQLiteOpenHelper dbHelper;

	/**
	 * Constructs a new data access object for room data.
	 * 
	 * @param context
	 *            the application context
	 */
	public RoomDataDAO(Context context) {
		this.dbHelper = new UpdatesDatabaseManager(context);
	}

	/**
	 * Returns the room data from database.
	 * 
	 * @param buildingId
	 *            the id of the building
	 * @param roomId
	 *            the id of the room
	 * @return
	 */
	public Map<String, String> getRoomData(String buildingId, String roomId) {
		String key;
		String value;
		String query = String.format(
				"SELECT * FROM %s WHERE %s = '%s' AND %s='%s'",
				UpdatesDatabaseManager.TABLE_NAME_UPDATES,
				UpdatesDatabaseManager.ID_COL, roomId,
				UpdatesDatabaseManager.COL_ID_BUILDING, buildingId);

		Cursor propertiesCursor = this.dbHelper.getReadableDatabase().rawQuery(
				query, null);
		HashMap<String, String> properties = new HashMap<String, String>();
		while (propertiesCursor.moveToNext()) {
			key = propertiesCursor.getString(KEY_POSITION);
			value = propertiesCursor.getString(VALUE_POSITION);
			properties.put(key, value);
		}
		propertiesCursor.close();
		return properties;
	}

	/**
	 * Inserts the data of a room into database.
	 * 
	 * @param buildingId
	 *            the id of the building
	 * @param roomId
	 *            the id of the room
	 * @param properties
	 *            the room data
	 */
	public void insertRoomData(String buildingId, String roomId,
			Map<String, String> properties) {
		for (String key : properties.keySet()) {
			String query = String.format(
					"INSERT INTO %s VALUES ('%s','%s','%s','%s')",
					UpdatesDatabaseManager.TABLE_NAME_UPDATES, buildingId,
					roomId, key, properties.get(key));
			this.dbHelper.getWritableDatabase().execSQL(query);
		}
	}

	/**
	 * Deletes the room data of a specific room.
	 * 
	 * @param buildingId
	 *            the id of the room
	 */
	public void deleteRoomData(String buildingId) {
		String query = String.format("DELETE FROM %s WHERE %s = '%s'",
				UpdatesDatabaseManager.TABLE_NAME_UPDATES,
				UpdatesDatabaseManager.COL_ID_BUILDING, buildingId);
		this.dbHelper.getWritableDatabase().execSQL(query);
	}

	/**
	 * Deletes all room data from database.
	 */
	public void deleteAllRoomData() {
		String query = String.format("DELETE FROM %s",
				UpdatesDatabaseManager.TABLE_NAME_UPDATES);
		this.dbHelper.getWritableDatabase().execSQL(query);
	}

}
